#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年7月16日

@author: chenyongbing
'''


import os,datetime,sys

import argparse
class mysqlBackUp():
    def __init__(self,mysqlPath=None,host='localhost',port=3306,user='root',password='password',db='db',save_db=None,testing=False):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db = db
        self.save_db = save_db
        self.testing = testing
        self.mysqlPath = mysqlPath
    def showTables(self):
        
        cmd = 'mysql -h%s -u%s -p%s -D %s -e "show tables"'%(self.host,self.user,self.password,self.db)
        if self.mysqlPath!=None:
            cmd = self.mysqlPath +'/' + cmd
        ret = os.popen(cmd)
        output =  ret.read()
        i = 0
        tables = []
        for line in output.split('\n'):
            line  = line.strip()
            if i==0 and line!="Tables_in_%s"%db:
                continue
            elif i==0:
                i= 1
                continue
            if len(line)>0:
                tables.append(line)
        return tables
      
      
    def dump(self,tables,backdir,day=None):
        if len(tables)==0:
            print 'UNKNOWN - no tables.'
            sys.exit(3)
        i=0;errList = []
        if self.save_db!=None:
            dir = backdir + '/' + self.save_db
        else:
            dir = backdir + '/' + self.db
        if day==None:
            day = (datetime.date.today()-datetime.timedelta(1)).strftime("%Y-%m-%d")
        
        for tab in tables:
            if tab not in ["mac_employee","mac_factory","company_config"]:continue
            i=0
            sdir = dir + '/' + tab + '/'
            if not os.path.exists(sdir):
                os.makedirs(sdir)
                
            sfile = sdir + tab +'.'+day+'.sql.gz'
            print 'Start Dump %s.%s To %s'%(self.db,tab,sfile)
            if os.path.exists(sfile):
                while 1:
                    i+=1
                    bfile = sdir + tab +'.'+day+'.sql.gz.bak.%s'%str(i)
                    if os.path.exists(bfile):
                        i+=1
                    else:
                        break
                if self.testing:
                    pass
                else:
                    os.popen('mv %s %s'%(sfile,bfile))
            
            cmd = 'mysqldump --single-transaction -h%s -u%s -p%s %s %s'%(self.host,self.user,self.password,self.db,tab) 
            if self.mysqlPath!=None:
                cmd = self.mysqlPath +'/' + cmd
            #cmd = cmd + ' --no-create-info --skip-add-drop-table'
            cmd = cmd + ' | gzip -c > %s'%(sfile)
            if self.testing:
                print cmd
            else:
                try:
                    os.popen(cmd)
                except Exception,error:
                    pass
            
            if not os.path.exists(sfile):
                errList.append(tab)
            
                
        if len(errList)!=0:
            print 'CRITICAL - %s tables dump error.'%(len(errList))
            sys.exit(2)
        else:
            print 'OK - mysql dump ok.'
            sys.exit(0)
         
    
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('-H', metavar=u'mysql host', default='localhost')
    parser.add_argument('-P', metavar=u'mysql port', default=3306,type=int)
    parser.add_argument('-u', metavar=u'user',default='root')
    parser.add_argument('-p', metavar=u'password', default='zhimatech')
    parser.add_argument('-d',metavar=u'database',default='zhimind')
    parser.add_argument('-f',metavar=u'backup path',required=True)
    parser.add_argument('--day',metavar=u'next day',default=None)
    parser.add_argument('--sdb',metavar=u'save db',default=None)
    parser.add_argument('--testing',metavar=u'testing',default=False)
    args = parser.parse_args()
    host = args.H
    port = args.P
    user = args.u
    password = args.p
    db = args.d
    bdir = args.f
    day = args.day
    save_db = args.sdb
    testing = args.testing

#     host = 'localhost'
#     user = 'root'
#     password = 'ipsec123'
#     db = 'zhimind'
#     bdir = '/Users/chenyongbing/DownLoad/mysql'
    
    myBackUp = mysqlBackUp(host=host,port=3306,user=user,password=password,db=db,save_db=save_db,testing=testing)
    tables = myBackUp.showTables()
    myBackUp.dump(tables,bdir,day=day)